//负责代理/劫持数据
import {
  statePool
} from "../compiler/state";
import {
  useReactive
} from "../reactive/index";
import {
  update
} from "../render";
import {
  hasOwnProperty,
  isEqual,
  isObject
} from "../shared/utils";

//定义getter和setter规则
const
  get = createGetter(),
  set = createSetter(),
  mutableHandler = {
    get,
    set
  };


//定义createGetter方法
/**
 * @returns get函数
 *  get函数：
 *  @target state对象
 *  @key state对象里的键名
 *  @receiver proxy对象
 */
function createGetter() {
  return function get(target, key, receiver) {
    // console.log(target);  {count: 0, name: "datian"}
    // console.log(key);  count
    // console.log(receiver);  Proxy {count: 0, name: "datian"}

    //Reflect.get() es6语法糖 相当于es5 get()
    const res = Reflect.get(target, key, receiver);

    // console.log('响应式获取:', target[key]);

    //如果是对象，则需要深度代理
    if (isObject(res)) {
      return useReactive(res);
    }
    //如果不是对象，直接返回数据本身
    return res;
  }
}

//定义createSetter方法
function createSetter() {
  return function set(target, key, value, receiver) {
    const
      isKeyExist = hasOwnProperty(target, key),
      //新旧值对比
      oldValue = target[key],
      res = Reflect.set(target, key, value, receiver);

    //如果不存在
    if (!isKeyExist) {
      // console.log('响应式新增:', key, value);
    } else if (!isEqual(value, oldValue)) {
      //存在，更改数据
      // console.log('响应式修改：', key, value);

      //视图更新
      update(statePool, key, value);
    }

    return res;
  }
}


export {
  mutableHandler
}